package com.knight.concurrent.chapter6;

/**
 * 控制线程执行多长时间
 *
 * @author: knight
 * @Date: 2019-03-04 20:38
 */
public class ThreadService {

    private Thread executeThread;

    private boolean finished = false;

    public void execute(Runnable task) {
        executeThread = new Thread() {
            @Override
            public void run() {
                Thread runner = new Thread(task);
                runner.setDaemon(true);
                runner.start();
                try {
                    runner.join();
                    finished = true;
                } catch (InterruptedException e) {
                    //
                }
            }
        };
        executeThread.start();
    }

    public void shutDown(long mills) {
        long currentTimeMillis = System.currentTimeMillis();

        while (!finished) {
            if ((System.currentTimeMillis() - currentTimeMillis) >= mills) {
                System.out.println("任务超时，需要结束");
                executeThread.interrupt();
                break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("线程被打断");
                break;
            }
        }
        finished = false;

    }
}
